<?php
namespace app\api\controller;
use app\api\model\Advertisement;
use app\api\model\CommentUser;
use app\api\model\CommonProblem;
use app\api\model\DiseaseUser;
use app\api\model\EscortType;
use app\api\model\NursingLang;
use app\api\model\OptionType;
use app\api\model\SearchTerm;
use app\api\model\StaffPeople;
use app\api\model\TermEmergency;
use app\api\model\Users;
use app\BaseController;
use Maowenke\PersonalWechatSdk\applet\WecateApplet;
use think\facade\Db;
use think\Request;

class Index extends BaseController
{
    /**获取首页数据
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(){
        echo '这是首页';
    }

    /**登录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sign_in(Request $request){
        $data = $request->param();
        $array = [
            'code|登录code'=>'require',
            'nickName|用户昵称'=>'require',
//            'avatarUrl'=>''
        ];
        $this->validate($data,$array);
        $config = config('wecate');
        $obj = new WecateApplet($config);
        $openid = $obj->getOpenId($data['code']);
        if(!$openid){
            return api_fail($obj->getMessage());
        }
        $user = Users::where('openid',$openid)
            ->withoutField('pwd')
            ->find();
        if(empty($user)){
            $newuser = [
                'name'=>$data['nickName'],
                'openid'=>$openid,
                'head_img'=>$data['avatarUrl']??'',
                'create_time'=>time(),
                'status'=>1,
                'update_time'=>time(),
                'create_time'=>time(),
            ];
            $user = Users::create($newuser);
        }else{
            if(isset($data['avatarUrl'])&&$data['avatarUrl']){
                $user->head_img = $data['avatarUrl'];
                $user->save();
            }
        }
        if(empty($user->token)){
            $user->token = Users::getToken($user->id);
        }
        $user = $user->toArray();
        if(isset($user['openid'])){
            unset($user['openid']);
        }
        return api_success('获取成功',$user);
    }

    /**获取首页数据
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_index(Request $request){
        $banner = Advertisement::where('status',1)
            ->where('identification','index_banner')
            ->field('id,identification,explain,img,href,explain')
            ->select()->toArray();
        $res['banner'] = $banner;
        $obj = new EscortType();
        $escorttype = $obj->getChild(0);
        $res['es_type'] = $escorttype;
        return api_success('获取成功',$res);
    }

    /**获取护理子分类
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_nursing_index(Request $request){
        $type_id = $request->param('type_id');
        if(empty($type_id)){
            return api_fail('请输入要查看的分类');
        }
        $type = EscortType::where('id',$type_id)
            ->find();
        if(empty($type)){
            return api_fail('分类不存在');
        }
        if($type->types==1||$type->types==2){
            $data = NursingLang::where('status',1)
                ->where('type_id',$type_id)
                ->field('id,name,introduction,img,home_money,no_hoime_money')
                ->order('sort desc')
                ->select()->toArray();
        }else{
            return api_fail('这个接口只提供护理方面的');
        }
        return api_success('获取成功',$data);
    }

    /**获取护理的详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function get_nursing_info(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请输入要查看的护理类型');
        }
        $nursing_lang = NursingLang::field('id,name,banner,duration,home_money,no_hoime_money,content,content_imgs,introduction,get_order_num_count')
//            ->withCount('getOrderNum')
            ->withCount('getComment')
            ->where('status',1)
            ->where('id',$id)
//            ->field('id,name,banner,duration,home_money,no_hoime_money,content,content_imgs,introduction')
            ->findOrEmpty()->toArray();
        if(empty($nursing_lang)){
            return api_fail('本分类已暂停预约');
        }
        return api_success('获取成功',$nursing_lang);
    }

    /**获取长期护理的详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_nursinglang_info(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请输入要查看的详情');
        }
        $nursing_lang = NursingLang::field('id,name,banner,duration,home_money,no_hoime_money,content,content_imgs,introduction')
            ->withCount('getOrderNum')
            ->withCount('getComment')
            ->where('status',1)
            ->where('id',$id)
//            ->field('id,name,banner,duration,home_money,no_hoime_money,content,content_imgs,introduction')
            ->findOrEmpty()->toArray();
        $option_type = OptionType::where('status',1)
            ->where('nursing_lang_id',$id)
            ->field('id,name,problem,disease_user_id')
            ->order('sort desc')
            ->select()->toArray();
        foreach ($option_type as $key=>$value){
            $child = DiseaseUser::where('status',1)
                ->where('option_type_id',$value['id'])
                ->where('nursing_lang_id',$id)
                ->field('id,name,money,is_default')
                ->order('sort desc')
                ->select()->toArray();
            $value['child'] = $child;
            $option_type[$key] = $value;
        }
        $nursing_lang['option_type'] = $option_type;
        return api_success('获取成功',$nursing_lang);
    }

    /**获取评论
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_comment_list(Request $request){
        $limit = $request->param('limit',10);
        $nursing_lang_id = $request->param('nursing_lang_id','');
        $staff_people_id = $request->param('staff_people_id','');
        $uid = $request->param('uid','');
        $nursing_order_id = $request->param('nursing_order_id','');
        if(empty($nursing_lang_id)&&empty($staff_people_id)&&empty($uid)&&empty($nursing_order_id)){
            return api_fail('请最少传一个条件');
        }
        $where = [
            ['status','=',1]
        ];
        if(!empty($nursing_lang_id)){
            $where[] = ['nursing_lang_id','=',$nursing_lang_id];
        }
        if(!empty($staff_people_id)){
            $where[] = ['staff_people_id','=',$staff_people_id];
        }
        if(!empty($uid)){
            $where[] = ['uid','=',$uid];
        }
        if(!empty($nursing_order_id)){
            $where[] = ['nursing_order_id','=',$nursing_order_id];
        }
        $data = CommentUser::where($where)
            ->with(['getuser'=>function($sql){
                $sql->field('id,name,head_img');
            }])
            ->withoutField('status,delete_time,update_time,sort,name')
            ->order('create_time desc')
            ->paginate($limit)->toArray();
        return api_success('获取成功',$data['data']);
    }

    /**获取护理员/护理老师
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_attendant_list(Request $request){
        $limit = $request->param('limit',10);
        $page = $request->param('page',1);
        $identity = $request->param('identity',1);
        $search = $request->param('search','');
        $min_age = $request->param('min_age');
        $max_age = $request->param('max_age');
        $min_entry = $request->param('min_entry');
        $max_entry = $request->param('max_entry');
        $sex = $request->param('sex');

        if(empty($identity)){
            return api_fail('请输入要查询的类型');
        }
        $where = [
            ['status','=',1],
            ['identity','=',$identity],
        ];
        if(!empty($sex)){
            $where[] = ['sex','=',$sex];
        }
        $whereOr = [];
        if(!empty($search)){
            $whereOr[] = ['name','like',"%$search%"];
            $whereOr[] = ['phone','like',"%$search%"];
            $whereOr[] = ['city','like',"%$search%"];
            $whereOr[] = ['introduce','like',"%$search%"];
            $whereOr[] = ['experience','like',"%$search%"];
            $whereOr[] = ['constellation','like',"%$search%"];
        }
        $data = StaffPeople::with(['getUserdata'=>function($sql){
//                $sql->field('id,birth_data,sex,heights,weights,certificates,service_num,service_time');
                $sql->withoutField('name,sort,create_time,update_time,status,delete_time,city,constellation,introduce,experience,certificates,sex,birth_data,entry_time');
            }])
            ->where($where)
            ->where(function ($sql)use ($whereOr){
                if(!empty($whereOr)){
                    $sql->whereOr($whereOr);
                }
            })
            ->field('id,name,identity,sex,fabulous,head_img,phone,fabulous,city,introduce,experience,constellation,(YEAR(CURDATE())-YEAR(birth_data)) as age,(YEAR(CURDATE())-YEAR(entry_time)) as entry');
        if(!empty($min_age)&&$min_age!=0){
            $data = $data->having('age>='.$min_age);
        }
        if(!empty($max_age)&&$max_age!=0){
            $data = $data->having('age<='.$max_age);
        }
        if(!empty($min_entry)&&$min_entry!=0){
            $data = $data->having('entry>='.$min_entry);
        }
        if(!empty($max_entry)&&$max_entry!=0){
            $data = $data->having('entry<='.$max_entry);
        }
        $data = $data->limit(($page-1)*$limit,$limit)->select()->toArray();
        return api_success('获取成功',$data);
    }

    /**获取护工/管理老师详情
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_attendant_info(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            return api_fail('请输入要查看的护工');
        }
        $data = StaffPeople::with(['getUserdata'=>function($sql){
//                $sql->field('id,birth_data,sex,heights,weights,certificates,service_num,service_time');
            $sql->withoutField('name,sort,introduce,create_time,update_time,status,delete_time,city,constellation,experience,sex,birth_data,entry_time');
        }])->where('status',1)
            ->where('id',$id)
            ->field('id,name,pid,identity,sex,head_img,phone,city,introduce,experience,constellation,(YEAR(CURDATE())-YEAR(birth_data)) as age,(YEAR(CURDATE())-YEAR(entry_time)) as entry')
            ->findOrEmpty()->toArray();
        if($data['identity']==1){
            $teacher = StaffPeople::where('id',$data['pid'])
                ->with(['getUserdata'=>function($sql){
                $sql->field('service_num,service_time,staff_people_id');
//                    $sql->withoutField('name,sort,create_time,update_time,status,delete_time,city,constellation,experience,sex,birth_data,entry_time');
                }])
                ->field('id,name,phone,head_img,fabulous')
                ->findOrEmpty()->toArray();
           $data['teacher'] = $teacher;
        }else{
            $child = StaffPeople::with(['getUserdata'=>function($sql){
//                $sql->field('id,birth_data,sex,heights,weights,certificates,service_num,service_time');
                $sql->withoutField('name,sort,introduce,create_time,update_time,status,delete_time,city,constellation,experience,sex,birth_data,entry_time');
            }])->where('status',1)
                ->where('pid',$data['id'])
                ->field('id,name,pid,identity,sex,head_img,phone,city,introduce,experience,constellation,(YEAR(CURDATE())-YEAR(birth_data)) as age,(YEAR(CURDATE())-YEAR(entry_time)) as entry')
                ->select()->toArray();
            $data['nursing_workers'] = $child;
        }
        return api_success('获取成功',$data);
    }
//
//    /**获取免费评估的选项
//     * @return \think\response\Json
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\DbException
//     * @throws \think\db\exception\ModelNotFoundException
//     */
//    public function get_assessment_option(){
//        $data = OptionType::where('status',1)
//            ->where('nursing_lang_id',8)
//            ->field('id,name,problem')
//            ->order('sort desc')
//            ->select()->toArray();
//        foreach ($data as $key=>$value){
//            $option = DiseaseUser::where('status',1)
//                ->where('option_type_id',$value['id'])
//                ->column('name');
//            $value['option'] = $option;
//            $data[$key] = $value;
//        }
//        $first_sentence = sysconfig('assessment','diyiju');
//        $last = sysconfig('assessment','zuihou');
//        $res['first_sentence'] = $first_sentence;
//        $res['last'] = $last;
//        $res['dialogue'] = $data;
//        return api_success('获取成功',$res);
//    }
    /**获取搜索选项
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_search(Request $request){
        $type = $request->param('type');
        if(empty($type)){
            return api_fail('请输入获取类型');
        }
        $where = [
            ['status','=',1]
        ];
        if($type=="age"){
            $where[] = ['type','=',1];
        }else{
            $where[] = ['type','=',2];
        }
        $data = SearchTerm::where($where)
            ->field('id,name,min_value,max_value')
            ->order('sort desc')
            ->select()->toArray();
        return api_success('获取成功',$data);
    }

    /**获取用户服务协议
     * @return \think\response\Json
     */
    public function get_agreement(){
        $data = sysconfig('agreement','duanqi_xieyi');
        return api_success('获取成功',['text'=>$data]);
    }

    /**获取常见问题
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function get_problem(Request $request){
        $limit = $request->param('limit');
        $data = CommonProblem::where('status',1)
            ->withoutField('sort,update_time,delete_time,status')
            ->order('sort desc')
            ->paginate($limit)
            ->toArray();
        return api_success('获取成功',$data['data']);
    }

    /**获取用户协议条款
     * @return \think\response\Json
     */
    public function user_agreement(){
        $data = sysconfig('agreement','user_xieyi_tiaokuan');
        return api_success('获取成功',['text'=>$data]);
    }

    /**获取公司介绍
     * @return \think\response\Json
     */
    public function company_introduction(){
        $data = sysconfig('company','jieshao');
        return api_success('获取成功',['text'=>$data]);
    }
}